import { defineStore } from 'pinia'
import useApiConfig from '@/utils/apiConfig'
import axios from 'axios'
import type {
  AsyncArticleData,
  AsyncColumnData,
  AsyncColumnsMember,
  AsyncColumnsTags,
  AsyncCommentData,
  AsyncCommentLike,
  AsyncComments,
  AsyncFollowigArticle,
  AsyncIdArticleData,
  AsyncIdColumnData,
  AsyncIdsToHistory,
  AsyncMsgLogs,
  AsyncMyArticles,
  AsyncMyColumns,
  AsyncPostMsgLogs,
  AsyncReturnLoginData,
  AsyncSaveFile,
  AsyncSearchFollowigColumns,
  AsyncSearchFollowigUsers,
  AsyncSearchResult,
  AsyncUserInfo,
  AsyncUserInfoData,
  AsyncUserList,
  AsyncWorkArticle,
  CommentData,
  CommentLike,
  ToFormData
} from '@/types/loginType'
export const useAsyncAxios = defineStore('useAsyncAxios', () => {
  // axios.defaults.headers.common['Authorization'] =
  const config = useApiConfig()
  const instance = axios.create({
    baseURL: config.baseURL
  })

  // 添加请求拦截器
  instance.interceptors.request.use(
    (config) => {
      const token = localStorage.getItem('token')
      config.headers['Authorization'] = `Bearer ${token}`
      // 返回修改后的配置
      return config
    },
    (error) => {
      // 对于请求配置错误，返回一个Promise.reject
      return Promise.reject(error)
    }
  )
  // 响应拦截器
  instance.interceptors.response.use(
    (response) => {
      return response
    },
    (error) => {
      if (error.response) {
        // 服务器返回了一个错误响应
        return { status: error.response.status, data: error.response.data }
      } else if (error.request) {
        // 请求已经发出，但没有收到响应
        return { status: -1, data: { msg: '请求超时' } }
      } else {
        // 发生了一个错误，但是没有请求
        return { status: -1, data: { msg: error.message } }
      }
    }
  )
  // 统一错误返回
  // { status: -1, msg: '错误描述信息' }
  // { status: 0, data: {} }

  function objectToFormData(obj: ToFormData) {
    const formData = new FormData()
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        formData.append(key, obj[key])
      }
    }
    return formData
  }

  // 登录请求
  async function login(data: FormData): Promise<AsyncReturnLoginData> {
    return await instance({
      method: 'post',
      url: config.login,
      data: data
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  async function loginJWT(): Promise<AsyncReturnLoginData> {
    return await instance({
      method: 'post',
      url: config.loginJWT
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 注册请求
  async function regist(data: FormData): Promise<AsyncReturnLoginData> {
    return await instance({
      method: 'post',
      url: config.regist,
      data: data
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  // 文章 card 组件
  // get /data 获取推荐文章数据
  async function getArticleData(): Promise<AsyncArticleData> {
    return await instance({
      method: 'get',
      url: config.getArticle
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // get article 获取指定id的文章的所有信息
  async function getArticle(id: string): Promise<AsyncIdArticleData> {
    return await instance({
      method: 'get',
      url: config.article,
      params: {
        articleId: id
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // post 收藏文章
  async function likeArticle(userId: string, articleId: string) {
    return await instance({
      method: 'post',
      url: config.articleLike,
      data: {
        userId,
        articleId
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  // get 获取指定 id文章的评论
  async function getComments(id: string): Promise<AsyncComments> {
    return await instance({
      method: 'get',
      url: config.commnets,
      params: {
        articleId: id
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // get column 获取推荐专栏
  async function getColumnsData(): Promise<AsyncColumnData> {
    return await instance({
      method: 'get',
      url: config.getColumn
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // get 获取指定 id 的专栏
  async function getColumn(id: string): Promise<AsyncIdColumnData> {
    return await instance({
      method: 'get',
      url: config.column,
      params: {
        columnId: id
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  async function likeColumn(userId: string, columnId: string) {
    return await instance({
      method: 'post',
      url: config.columnLike,
      data: {
        userId,
        columnId
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  // post 点赞评论
  async function sendLike(data: CommentLike): Promise<AsyncCommentLike> {
    return await instance({
      method: 'post',
      url: config.sendLike,
      data: objectToFormData(data)
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // post 发送评论
  async function sendComment(data: CommentData): Promise<AsyncCommentData> {
    return await instance({
      method: 'post',
      url: config.sendComment,
      data: objectToFormData(data)
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  // 订阅 followig组件
  // 获取订阅的用户列表
  async function searchFollowigUsers(id: string): Promise<AsyncSearchFollowigUsers> {
    return await instance({
      method: 'get',
      url: config.searchFollowigUsers,
      params: {
        userId: id
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 获取订阅的专栏列表
  async function searchFollowigColumns(id: string): Promise<AsyncSearchFollowigColumns> {
    return await instance({
      method: 'get',
      url: config.SearchFollowigColumns,
      params: {
        userId: id
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 获取订阅的用户或专栏下的文章
  async function searchFollowigColumnsOrUsersArticle(id: string): Promise<AsyncFollowigArticle> {
    try {
      const data = await instance({
        method: 'get',
        url: config.followigColumnsArticle,
        params: {
          columnId: id
        }
      })
      return data
    } catch (error) {
      return { status: -1, data: { msg: '发生错误' } }
    }
  }

  // 历史组件
  async function getTimeArticles(ids: string[]): Promise<AsyncIdsToHistory> {
    return await instance({
      method: 'get',
      url: config.idsTohistory,
      params: {
        ids
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  // 通信组件
  async function getMessageUserList(id: string): Promise<AsyncUserList> {
    return await instance({
      method: 'get',
      url: config.messageUsers,
      params: {
        userId: id
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  async function getMessageLogs(id: string, sendId: string): Promise<AsyncMsgLogs> {
    return await instance({
      method: 'get',
      url: config.messageLogs,
      params: {
        userId: id,
        sendTo: sendId
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 发送消息
  async function postMessageToUser(formData: FormData): Promise<AsyncPostMsgLogs> {
    return await instance({
      method: 'post',
      url: config.postMessageToUser,
      data: formData
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  // 编辑
  // 我的文章
  async function getMyArticles(id: string): Promise<AsyncMyArticles> {
    return await instance({
      method: 'get',
      url: config.editArticle,
      params: {
        userId: id
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 我的专栏
  async function getMyColumns(id: string): Promise<AsyncMyColumns> {
    return await instance({
      method: 'get',
      url: config.editColumns,
      params: { userId: id }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 专栏下的成员
  async function getColumnsMember(columnId: string): Promise<AsyncColumnsMember> {
    return await instance({
      method: 'get',
      url: config.editMember,
      params: { columnId }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 提交修改
  // 修改专栏
  async function postColumns(formData: FormData): Promise<AsyncColumnData> {
    try {
      const { status, data } = await instance({
        method: 'post',
        url: config.postColumnData,
        data: formData
      })
      return { status: status, data: { msg: '修改专栏成功' } }
    } catch (error) {
      return { status: -1, data: { msg: '修改专栏资料失败' } }
    }
  }
  // 修改个人信息
  async function postUserInfo(formData: FormData): Promise<AsyncUserInfoData> {
    return await instance({
      method: 'post',
      url: config.postUserInfoData,
      data: formData
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  // userinfo
  // 专栏info
  async function getUserInfo(id: string): Promise<AsyncUserInfo> {
    return await instance({
      method: 'get',
      url: config.userInfo,
      params: { userId: id }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 订阅用户
  async function likeUser(id: string, userId: string) {
    return await instance({
      method: 'post',
      url: config.likeUser,
      data: {
        followerId: id,
        userId
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  // 搜索
  async function search(value: string, type: undefined | number): Promise<AsyncSearchResult> {
    try {
      const data = await instance({
        method: 'get',
        url: config.search,
        params: { value, type }
      })
      return data.data
    } catch (error) {
      return { status: -1, data: { msg: '搜索数据失败' } }
    }
  }

  // 获取文章的可选择添加的标签专栏数据
  async function getColumnsTagsSelected(articleId: string): Promise<AsyncColumnsTags> {
    return await instance({
      method: 'get',
      url: config.workSelect,
      params: {
        articleId
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 获取保存的文件信息
  async function getSaveArticle(articleId: string): Promise<AsyncWorkArticle> {
    console.log(0)

    return await instance({
      method: 'get',
      url: config.getSaveArticle,
      params: {
        articleId
      }
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }
  // 发送编写的文件
  async function postSaveArticle(formData: FormData): Promise<AsyncSaveFile> {
    // public 0 为非公开 1 为公开
    return await instance({
      method: 'post',
      url: config.saveArticle,
      data: formData
    })
      .then((result) => {
        return result
      })
      .catch((error) => {
        console.error(error)
        throw error
      })
  }

  // 发送图像
  async function postImgToUrl(data: FileList) {
    return await instance({
      method: 'post',
      url: config.imgToUrlPath,
      data: data
    })
  }

  return {
    login,
    loginJWT,
    regist,
    getArticleData,
    getArticle,
    likeArticle,
    getComments,
    getColumnsData,
    getColumn,
    likeColumn,
    sendLike,
    sendComment,
    searchFollowigUsers,
    searchFollowigColumns,
    searchFollowigColumnsOrUsersArticle,
    getTimeArticles,
    getMessageUserList,
    getMessageLogs,
    postMessageToUser,
    getMyArticles,
    getMyColumns,
    getColumnsMember,
    postColumns,
    postUserInfo,
    getUserInfo,
    likeUser,
    search,
    getColumnsTagsSelected,
    postSaveArticle,
    getSaveArticle,
    postImgToUrl
  }
})
